package com.aps.apspda.activity;

import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.aps.apspda.R;
import com.aps.apspda.adapter.PopDownAreaListAdapter;
import com.aps.apspda.base.BaseActivity;
import com.aps.apspda.callback.CommonCallback;
import com.aps.apspda.callback.DialogEntityCallBack;
import com.aps.apspda.callback.EntityCallBack;
import com.aps.apspda.dialog.DownloadFragmentDialog;
import com.aps.apspda.dialog.IpSettingVerifyFragmentDialog;
import com.aps.apspda.entity.BaseEntity;
import com.aps.apspda.entity.LoginEntity;
import com.aps.apspda.entity.VersionEntity;
import com.aps.apspda.myview.ClearEditText;
import com.aps.apspda.myview.PasswordEditText;
import com.aps.apspda.utils.AntiShake;
import com.aps.apspda.utils.AppUtils;
import com.aps.apspda.utils.NetUtils;
import com.aps.apspda.utils.StaticMembers;
import com.aps.apspda.utils.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;

public class LoginActivity extends BaseActivity {

    @BindView(R.id.etMobile)
    ClearEditText etMobile;
    @BindView(R.id.etPassword)
    PasswordEditText etPassword;
    @BindView(R.id.tvArea)
    TextView tvArea;
    @BindView(R.id.ivArrow)
    ImageView ivArrow;
    @BindView(R.id.flArea)
    FrameLayout flArea;
    @BindView(R.id.rlParent)
    RelativeLayout rlParent;
    @BindView(R.id.tvVersion)
    TextView tvVersion;
    private PopupWindow titlePop;
    private View popView;
    private Animation animation, animationDismiss;
    private RecyclerView lvDownList;
    private PopDownAreaListAdapter popDownAreaListAdapter;
    private int type = 0;
    private String TAG_USER_LOGIN = "user_login";
    private DownloadFragmentDialog dialog;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_login;
    }

    @Override
    protected void initView() {
        popView = getLayoutInflater().inflate(R.layout.popupwindow_down_list_select, null);
        lvDownList = popView.findViewById(R.id.lvDownList);
        lvDownList.setLayoutManager(new LinearLayoutManager(LoginActivity.this));
        lvDownList.setItemAnimator(new DefaultItemAnimator());

        etMobile.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (start == 0 && before == 0 && count > 1) {
//                    etPassword.requestFocus();
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    @Override
    protected void initData() {
        setCallback(etMobile);
        AppUtils.deleteLog();
        final List<String> list = new ArrayList<>();
        list.add("FAB-A");
        popDownAreaListAdapter = new PopDownAreaListAdapter(list);
        popDownAreaListAdapter.openLoadAnimation(BaseQuickAdapter.ALPHAIN);
        popDownAreaListAdapter.isFirstOnly(false);
        popDownAreaListAdapter.setCurrentSelect(type);
        lvDownList.setAdapter(popDownAreaListAdapter);
        tvVersion.setText("V" + AppUtils.getVerName());
        popDownAreaListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                type = position;
                popDownAreaListAdapter.setCurrentSelect(type);
                popDownAreaListAdapter.notifyDataSetChanged();
                tvArea.setText(list.get(position));
                titlePop.dismiss();
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        OkGo.getInstance().cancelTag(this);
    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (titlePop == null) {
            titlePop = new PopupWindow(popView, flArea.getWidth(), RelativeLayout.LayoutParams.MATCH_PARENT, true);
            titlePop.setAnimationStyle(R.style.PopupWindowCenterAnimation);
            titlePop.setBackgroundDrawable(new BitmapDrawable());
            titlePop.setFocusable(true);
            titlePop.setOutsideTouchable(true);
            titlePop.setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    if (animationDismiss == null) {
                        animationDismiss = new RotateAnimation(180f, 0f, Animation.RELATIVE_TO_SELF,
                                0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                        animationDismiss.setDuration(500);
                        animationDismiss.setFillAfter(true);
                    }
                    ivArrow.startAnimation(animationDismiss);
                }
            });
        }
    }

//    private boolean sss(String str){
//            String[] strs;
//            if (str.contains(";")) {
//                strs = str.split(";");
//            } else {
//                strs = new String[1];
//                strs[0] = str;
//            }
//            if (strs.length == 4) {
//                return true;
//            } else if (strs.length == 5) {
//                return true;
//            } else if (strs.length == 1 && str.length() > 15) {
//                if (str.substring(str.length() - 15, str.length() - 14).equals("H")) {
//                    str = str.substring(str.length() - 15, str.length() - 3);
//                    String ssss = str;
//                    return true;
//                } else if (str.substring(str.length() - 16, str.length() - 15).equals("H")) {
//                    str = str.substring(0, str.length() - 1);
//                    str = str.substring(str.length() - 15, str.length() - 3);
//                    String ssss = str;
//                    return true;
//                } else {
//                    return false;
//                }
//            } else {
//                return false;
//            }
//    }

    @OnClick({R.id.btnLogin, R.id.flArea, R.id.ivSetting})
    public void onClick(View view) {
        if (AntiShake.check(view.getId())) {    //判断是否多次点击
            ToastUtils.showFreeToast("请勿重复点击",
                    LoginActivity.this, false, Toast.LENGTH_SHORT);
            return;
        }
        switch (view.getId()) {
            case R.id.flArea:
                showTypePop();
                break;
            case R.id.ivSetting:
                IpSettingVerifyFragmentDialog ipSettingVerifyFragmentDialog = new IpSettingVerifyFragmentDialog();
                ipSettingVerifyFragmentDialog.setData("管理员密码验证", null);
                ipSettingVerifyFragmentDialog.show(getSupportFragmentManager(), "PASSWORD_VERIFY");
                break;
            case R.id.btnLogin:
                if (etMobile.getText().toString().trim().length() == 0) {
                    ToastUtils.showFreeToast("请输入用户名", this, false, Toast.LENGTH_SHORT);
                    return;
                }
                if (etPassword.getText().toString().trim().length() == 0) {
                    ToastUtils.showFreeToast("请输入密码", this, false, Toast.LENGTH_SHORT);
                    return;
                }
                requestLogin(etMobile.getText().toString().trim(), etPassword.getText().toString().trim(), tvArea.getText().toString());
                break;
        }
    }

    private void showTypePop() {
        if (titlePop.isShowing()) {
            titlePop.dismiss();
        } else {
            if (animation == null) {
                animation = new RotateAnimation(0f, 180f, Animation.RELATIVE_TO_SELF,
                        0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
                animation.setDuration(500);
                animation.setFillAfter(true);
            }
            ivArrow.startAnimation(animation);
            AppUtils.showAsDropDown(titlePop, flArea, 0, 0);
        }
    }

    private void requestLogin(String phone, String pwd, String area) {
        EntityCallBack<BaseEntity<LoginEntity>> callBack = new DialogEntityCallBack<BaseEntity<LoginEntity>>
                (new TypeToken<BaseEntity<LoginEntity>>() {
                }.getType(), getSupportFragmentManager(), TAG_USER_LOGIN) {

            @Override
            public void onSuccess
                    (final Response<BaseEntity<LoginEntity>> response) {
                loadSuccess(response.body(), new CommonCallback() {
                    @Override
                    public void onSuccess() {
                        LoginEntity loginEntity = response.body().getData();
                        if (loginEntity.getLOGINRESULT()) {
                            if (loginEntity.getISACTIVE()) {
                                StaticMembers.CUR_USER = loginEntity;
                                ToastUtils.showFreeToast("登陆成功",
                                        LoginActivity.this, true, Toast.LENGTH_SHORT);
                                startActivity(new Intent(LoginActivity.this, HomeActivity.class));
                                LoginActivity.this.finish();
                            } else {
                                ToastUtils.showFreeToast(loginEntity.getMESSAGE(),
                                        LoginActivity.this, true, Toast.LENGTH_SHORT);
                            }
                        } else {
                            ToastUtils.showFreeToast(loginEntity.getMESSAGE(),
                                    LoginActivity.this, true, Toast.LENGTH_SHORT);
                        }

                    }
                });
            }

            @Override
            public void onError
                    (Response<BaseEntity<LoginEntity>> response) {
                super.onError(response);
                loadError(response.getException(), "ClientLogin");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("USERNAME", phone);
        map.put("PASSWORD", pwd);
        map.put("AREA", area);
        NetUtils.requestNet(TAG_USER_LOGIN, "/ClientLogin", map, callBack);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (dialog == null) {
            requestUpdate();
        }
    }

    private void requestUpdate() {
        EntityCallBack<BaseEntity<VersionEntity>> callBack = new EntityCallBack<BaseEntity<VersionEntity>>
                (new TypeToken<BaseEntity<VersionEntity>>() {
                }.getType()) {

            @Override
            public void onSuccess
                    (Response<BaseEntity<VersionEntity>> response) {
                if (response.body().isSuccess(LoginActivity.this)) {
                    dialog = new DownloadFragmentDialog();
                    dialog.setData(response.body().getData());
                    dialog.show(getSupportFragmentManager(), "dialog_down_new");
                }
            }

            @Override
            public void onError
                    (Response<BaseEntity<VersionEntity>> response) {
                super.onError(response);
                AppUtils.saveErrorMessages(response.getException(), "UpGradeApp");
            }
        };

        Map<String, String> map = new HashMap<>();
        map.put("version", String.valueOf(StaticMembers.VERSION_CODE));
        NetUtils.requestNet(this, "/UpGradeApp", map, callBack);
    }
}
